package com.yueya.basic.user.action;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.kit.JsonKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;
import com.yueya.basic.dept.model.Dept;
import com.yueya.basic.dept.model.DeptUser;
import com.yueya.basic.dict.model.Dict;
import com.yueya.basic.role.model.Role;
import com.yueya.basic.role.model.RoleUser;
import com.yueya.basic.user.model.User;
import com.yueya.basic.user.model.UserBase;
import com.yueya.common.action.BaseController;
import com.yueya.common.model.Json;
import com.yueya.common.model.Tree;
import com.yueya.common.util.DateFormat;
import com.yueya.common.util.Encrypt;
import com.yueya.common.util.RandomUtil;
import com.yueya.common.util.UploadUtil;
import com.yueya.config.GlobalParam;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

/**
 * UserController
 */
public class UserController extends BaseController {

	Map<String, Object> map = new HashMap<String, Object>();

	public void index() {
		this.setAttr("loginname", getLoginName());
		render("/WEB-INF/views/basic/user/user_list.jsp");
	}

	public void s_user_list() {
		this.setAttr("loginname", getLoginName());
		this.setAttr("pageParentId", getPara("pageParentId").trim());

		render("/WEB-INF/views/basic/user/s_user_list.jsp");
	}

	// 分页列表
	public void getListPager() {
		map.clear();
		if (getPara("namestr") != null) {
			map.put("name", getPara("namestr").trim());
		}
		if (getPara("deptstr") != null) {
			map.put("deptstr", getPara("deptstr"));
		}
		if (getPara("statusstr") != null) {
			map.put("statusstr", getPara("statusstr").trim());
		}

		Page<Record> page = User.service.pagination(getPage(), getRows(), map);
		jsonMap.put("total", page.getTotalRow());
		jsonMap.put("rows", page.getList());
		renderJson(JsonKit.toJson(jsonMap));
	}

	public void getList() {
		String sql = "from t_user where del_flag = 0 ";

		Page<User> page = User.dao.paginate(getPage(), getRows(), "select * ", sql);
		jsonMap.put("total", page.getTotalRow());
		jsonMap.put("rows", page.getList());
		renderJson(JsonKit.toJson(jsonMap));
	}

	// 保存
	public void save() {

		User user = getModel(User.class);
		UserBase userBase = getModel(UserBase.class);
		DeptUser deptUser = getModel(DeptUser.class);
		Json j = new Json();
		boolean bl = User.service.save(user, userBase, deptUser);

		if (bl == true) {
			j.setSuccess(true);
			j.setMsg("新增用户成功");
		} else {
			j.setSuccess(false);
			j.setMsg("操作失败");
		}

		this.renderJson(j);
	}

	// 判断用户名是否存在
	public void isExistUser() {
		User user = getModel(User.class);
		User.service.isExistLogin_name(user.getStr("login_name"));
	}

	public void doAdd() {
		if (getPara("pid") != null) {
			this.setAttr("pid", getPara("pid"));
		}
		this.render("/WEB-INF/views/basic/user/user_edit.jsp");
	}

	public void doEdit() {
		String id = this.getPara("id");
		User user = User.dao.findById(id);
		DeptUser du = DeptUser.dao.findByUserId(id);
		setAttr("user", user);
		setAttr("dept_name", Dept.dao.findById(du.getStr("dept_id")).getStr("dept_name"));
		UserBase ue = UserBase.dao.findByUserId(id);
		setAttr("userBase", ue);
		setAttr("deptUser", du);
		setAttr("visit_path", GlobalParam.getAttUrl());
		this.render("/WEB-INF/views/basic/user/user_edit.jsp");
	}

	public void upwd() {
		this.render("/WEB-INF/views/basic/user/upwd.jsp");
	}

	public void updatepwd() {
		User user = getModel(User.class);
		int num = Db.update("update t_user set pwd=? where user_id=?", Encrypt.doStrByMD5(user.getStr("pwd")),
				user.getStr("user_id"));
		Json j = new Json();
		if (num > 0) {
			j.setSuccess(true);
			j.setMsg("密码成功!");
		} else {
			j.setSuccess(false);
			j.setMsg("密码失败!");
		}
		this.renderJson(j);
	}

	public void removeUser() {
		User user = User.dao.findById(getPara("id"));
		boolean bl = false;
		if (user != null) {
			user.set("del_flag", "1");
			bl = user.update();
		}
		Json j = new Json();
		if (bl) {
			j.setSuccess(true);
			j.setMsg("删除成功!");
		} else {
			j.setSuccess(false);
			j.setMsg("删除失败!");
		}
		this.renderJson(j);
	}

	public void bathRemoveUser() {
		Boolean bl = false;
		String idsStr = this.getPara("ids");
		if (idsStr != null) {
			String[] ids = idsStr.split(";");
			User user = null;
			for (int i = 0; i < ids.length; i++) {

				if (!"".equals(ids[i]) && ids[i] != null) {
					user = User.dao.findById(ids[i]);
					user.set("del_flag", 1);
					if (user.update()) {
						bl = true;
					} else {
						bl = false;
						break;
					}
				}

			}
		}

		Json j = new Json();
		if (bl == true) {
			j.setSuccess(true);
			j.setMsg("删除成功!");
		} else {
			j.setSuccess(false);
			j.setMsg("删除失败!");
		}
		this.renderJson(j);
	}

	public void deleteUser() {

		String id = getPara("id");
		boolean bl = User.dao.deleteById(id);
		Json j = new Json();
		if (bl) {
			j.setSuccess(true);
			j.setMsg("删除成功!");
		} else {
			j.setSuccess(false);
			j.setMsg("删除失败!");
		}
		this.renderJson(j);
	}

	public void bathDeleteUser() {
		Boolean bl = false;
		String idsStr = this.getPara("ids");
		if (idsStr != null) {
			String[] ids = idsStr.split(";");
			User user = null;
			for (int i = 0; i < ids.length; i++) {

				if (!"".equals(ids[i]) && ids[i] != null) {
					user = User.dao.findById(ids[i]);
					if (user.delete()) {
						bl = true;
					} else {
						bl = false;
						break;
					}
				}

			}
		}

		Json j = new Json();
		if (bl == true) {
			j.setSuccess(true);
			j.setMsg("删除成功!");
		} else {
			j.setSuccess(false);
			j.setMsg("删除失败!");
		}
		this.renderJson(j);
	}

	public void getUserByDept() {
		String deptid = this.getPara("deptid");
		List<User> list = User.service.getUserListByDeptId(deptid);
		renderJson(list);
	}

	public void setRole() {
		String userid = this.getPara("id");
		setAttr("userid", userid);

		List<Role> roles = Role.dao.getAllRole();
		setAttr("roles", roles);

		List<RoleUser> roleusers = RoleUser.dao.getListByUserId(userid);
		setAttr("roleusers", roleusers);
		this.render("/WEB-INF/views/basic/user/user_role.jsp");
	}

	public void saveUserRole() {
		String userid = this.getPara("userid");
		String[] roleids = this.getParaValues("roleids");

		boolean bl = RoleUser.service.saveUserRoles(userid, roleids);

		Json j = new Json();
		if (bl == true) {
			j.setSuccess(true);
			j.setMsg("操作成功!");
		} else {
			j.setSuccess(false);
			j.setMsg("操作失败!");
		}
		this.renderJson(j);
	}

	public void getUserJson() {
		renderJson(User.service.getUserinfoAndDept());
	}

	// 初始化密码
	public void initPwd() {
		String id = this.getPara("id");

		boolean bl = false;
		User u = User.dao.findById(id);
		String pwd = RandomUtil.getLetterNumber(6);
		String enPwd = Encrypt.doStrByMD5(pwd);

		u.set("PASSWORD", enPwd);
		u.set("PWD", pwd);
		bl = u.update();
		Json j = new Json();
		if (bl == true) {
			j.setSuccess(true);
			j.setMsg("操作成功!");
		} else {
			j.setSuccess(false);
			j.setMsg("操作失败!");
		}
		this.renderJson(j);
	}

	public void initAllPwd() {

		boolean bl = User.service.initAllPwd();

		Json j = new Json();
		if (bl == true) {
			j.setSuccess(true);
			j.setMsg("操作成功!");
		} else {
			j.setSuccess(false);
			j.setMsg("操作失败!");
		}
		this.renderJson(j);
	}

	public void exportUser() {
		String ids = this.getPara("cks");
		String[] idss = null;
		if (ids != null && !"".equals(ids)) {
			idss = ids.split(";");
		}
		String path = PathKit.getWebRootPath();
		String savePath = null;
		// 导出留言
		try {
			String date = DateFormat.getDate("yyyy-MM-dd");
			List<User> li = null;
			String inid = "";
			String sql = "";
			if (idss != null && idss.length > 0) {
				for (int i = 0; i < idss.length; i++) {
					if (i != 0) {
						inid += ",";
					}
					inid += "'" + idss[i] + "'";
				}
				sql = "select u.id,u.user_name,u.user_no,u.pwd,d.dept_name,vi.dept_name as village,town.dept_name as town "
						+ "from t_user u " + "left join t_wlkj_dept_inf d on d.id = u.dept_id "
						+ "left join t_wlkj_rjhd_cadre c on c.user_id = u.id "
						+ "left join t_wlkj_dept_inf vi on c.cadre_contant = vi.id "
						+ "left join t_wlkj_dept_inf town on town.id = vi.parent_id "
						+ "where u.del_flag = '0' and u.status = '1' and u.login_name !='admin' and u.id in (" + inid
						+ ") order by u.order_id asc";
				System.out.println(sql);
				li = User.dao.find(sql);
			} else {
				sql = "select u.id,u.user_name,u.user_no,u.pwd,d.dept_name,vi.dept_name as village,town.dept_name as town "
						+ "from t_user u " + "left join t_wlkj_dept_inf d on d.id = u.dept_id "
						+ "left join t_wlkj_rjhd_cadre c on c.user_id = u.id "
						+ "left join t_wlkj_dept_inf vi on c.cadre_contant = vi.id "
						+ "left join t_wlkj_dept_inf town on town.id = vi.parent_id "
						+ "where u.del_flag = '0' and u.status = '1' and u.login_name !='admin' order by u.order_id asc";
				li = User.dao.find(sql);
			}

			savePath = path + "\\" + date + "(user).xls";
			WritableWorkbook wwb = Workbook.createWorkbook(new File(savePath));
			WritableSheet ws;
			ws = wwb.createSheet("sheet1", 0);
			WritableFont font = new WritableFont(WritableFont.createFont("宋体"), 10, WritableFont.BOLD);

			WritableCellFormat formatTitle = new WritableCellFormat(font);
			formatTitle.setAlignment(Alignment.CENTRE);// 水平居中
			formatTitle.setVerticalAlignment(VerticalAlignment.CENTRE);// 上下居中
			formatTitle.setBorder(Border.ALL, BorderLineStyle.THIN);
			// 内容区
			WritableFont fontContent = new WritableFont(WritableFont.createFont("宋体"), 10);
			// 居中格式
			WritableCellFormat formatContent = new WritableCellFormat(fontContent);
			formatContent.setBorder(Border.ALL, BorderLineStyle.THIN);
			formatContent.setWrap(true);
			formatContent.setVerticalAlignment(VerticalAlignment.CENTRE);// 上下居中
			formatContent.setAlignment(Alignment.CENTRE);// 水平居中
			// 居左格式
			WritableCellFormat formatContent1 = new WritableCellFormat(fontContent);
			formatContent1.setBorder(Border.ALL, BorderLineStyle.THIN);
			formatContent1.setWrap(true);
			formatContent1.setVerticalAlignment(VerticalAlignment.TOP);

			Label labeld = new jxl.write.Label(0, 0, "单位", formatTitle);
			ws.addCell(labeld);
			ws.setColumnView(0, 50);// 设置列宽

			labeld = new jxl.write.Label(1, 0, "乡镇", formatTitle);
			ws.addCell(labeld);
			ws.setColumnView(1, 25);// 设置列宽

			labeld = new jxl.write.Label(2, 0, "村居", formatTitle);
			ws.addCell(labeld);
			ws.setColumnView(2, 25);// 设置列宽

			labeld = new jxl.write.Label(3, 0, "姓名", formatTitle);
			ws.addCell(labeld);
			ws.setColumnView(3, 25);// 设置列宽

			labeld = new jxl.write.Label(4, 0, "编号", formatTitle);
			ws.addCell(labeld);
			ws.setColumnView(4, 25);// 设置列宽

			labeld = new jxl.write.Label(5, 0, "密码", formatTitle);
			ws.addCell(labeld);
			ws.setColumnView(5, 25);// 设置列宽

			ws.mergeCells(0, 0, 0, 1);
			ws.mergeCells(1, 0, 1, 1);
			ws.mergeCells(2, 0, 2, 1);
			ws.mergeCells(3, 0, 3, 1);
			ws.mergeCells(4, 0, 4, 1);
			ws.mergeCells(5, 0, 5, 1);
			int startRow = 1;// 内容的开始行（第三行）

			User user = null;
			for (int i = 0; i < li.size(); i++) {
				user = (User) li.get(i);
				labeld = new jxl.write.Label(0, startRow + 1, user.getStr("dept_name"), formatContent);
				ws.addCell(labeld);

				labeld = new jxl.write.Label(1, startRow + 1, user.getStr("town"), formatContent);
				ws.addCell(labeld);

				labeld = new jxl.write.Label(2, startRow + 1, user.getStr("village"), formatContent);
				ws.addCell(labeld);

				labeld = new jxl.write.Label(3, startRow + 1, user.getStr("user_name"), formatContent);
				ws.addCell(labeld);

				labeld = new jxl.write.Label(4, startRow + 1, user.getStr("user_no"), formatContent);
				ws.addCell(labeld);

				labeld = new jxl.write.Label(5, startRow + 1, user.getStr("pwd"), formatContent);
				ws.addCell(labeld);
				startRow++;
			}
			wwb.write();
			wwb.close();
			// 导出实录

		} catch (Exception e) {
			e.printStackTrace();
		}
		renderFile(new File(savePath));
	}

	public void listTree() {
		String deptArrs = this.getPara("deptslist");

		List<String> list = new ArrayList<String>();
		String[] arrs = deptArrs.split(",");
		for (int i = 0; i < arrs.length; i++) {
			list.add(arrs[i]);
		}
		// List<Tree> rt = Dept.service.toTreeList(Dept.dao._r(), "");// 为根节点
		// <Tree> rl = Dept.service.toTreeListToDeptid(Dept.dao._rtl(),
		// list);
		// List<Tree> ret = Dept.service.splitTree(rt, rl, rl);
		ArrayList<Tree> l = new ArrayList<Tree>();
		l.add(Dept.service.recursiveTree("000", list));

		renderJson(JsonKit.toJson(l));
	}

	// 图片上传
	public void uploadInfo() {
		Map<String, Object> uploadMap = null;
		UploadFile upfile = this.getFile();
		if (StrKit.notNull(upfile)) {
			File file = upfile.getFile();
			String filedir = "/avatar"; // 存放目录
			uploadMap = UploadUtil.uploadFile(Dict.dao.getValue("attachment_upload_save_path"), upfile.getFileName(),
					filedir, file);
			if ("1".equals(uploadMap.get("flag").toString())) {
				String savePath = (String) uploadMap.get("savepath");
				uploadMap.put("savepath", GlobalParam.getAttUrl() + savePath);
				uploadMap.put("relativepath", savePath);
				uploadMap.put("filename", upfile.getFileName());
				file.delete();
			}
		}
		renderJson(uploadMap);

	}
}
